<template>
  <div>
    <ButtonGroup :options="buttons" @click="handleButtonClick" />
    <p-table
      class="table-list-container"
      :custom-header-row="customHeaderRowMinxin"
      table-layout="auto"
      row-key="id"
      :columns="columns"
      bordered
      :scroll="{ x: true, y: 200 }"
      :pagination="false"
      :data-source="dataSource"
      :row-selection="rowSelectionMixin"
      @change="handleTableChange"
    >
      <template slot="salesGroup" slot-scope="text, record, index">
        <SelectOrg
          :value="text"
          :has-all="false"
          :options="orgGroupOptions"
          :label-in-value="true"
          :allow-clear="false"
          :parent-id="parentId"
          @input="handleInputChange($event, text, record, index, 'salesGroup')"
        />
      </template>
      <template slot="responsibleId" slot-scope="text, record, index">
        <div class="item-container">
          <p-icon type="user" style="margin-right: 8px" />
          <SelectUser
            :value="text"
            :has-all="false"
            :allow-clear="false"
            :parent-id="record.salesGroup.key"
            @input="
              handleInputChange($event, text, record, index, 'responsibleId')
            "
          />
        </div>
      </template>
      <template slot="kapmGroup" slot-scope="text, record, index">
        <SelectOrg
          :value="text"
          :has-all="false"
          :options="orgKapmOptions"
          :has-default-value="!planId"
          :label-in-value="true"
          :allow-clear="false"
          :parent-id="parentId"
          @input="handleInputChange($event, text, record, index, 'kapmGroup')"
        />
      </template>
    </p-table>
    <DialogSaveTemplate
      :visible.sync="visibleDialog"
      :data-source="templateData"
      :sales-organization="parentId"
      @change="handleDialogChange"
    />
    <DialogUseTemplate
      :visible.sync="visibleDialogUse"
      :sales-organization="parentId"
      @change="handleDialogUseChange"
    />
  </div>
</template>

<script>
import mixinTable from '@/mixins/mixin-table.js';
import SelectUser from '@/components/select/SelectUser.vue';
import DialogSaveTemplate from '@/components/dialog/DialogSaveTemplate.vue';
import DialogUseTemplate from '@/components/dialog/DialogUseTemplate.vue';
import { postOrganizationInfo } from '@/api/public.js';

let index = 0;
const createDefaultItem = () => ({
  id: index++,
  salesGroup: '',
  kapmGroup: '',
  responsibleId: '',
  isTemplate: 0,
  templateName: undefined,
});
export default {
  components: {
    SelectUser,
    DialogSaveTemplate,
    DialogUseTemplate,
  },
  mixins: [mixinTable],
  props: {
    parentId: {
      type: [String, Number],
      default: undefined,
    },
    dataSource: {
      type: Array,
      default: () => [],
    },
    planId: {
      type: [String, Number],
      default: '',
    },
    buttons: {
      type: [Array],
      default: () => [
        {
          key: 'add',
          type: 'primary',
          label: '新增',
          icon: 'plus',
        },
        {
          key: 'delete',
          label: '删除',
          icon: 'delete',
        },
        {
          key: 'useTemplate',
          label: '使用模板',
        },
        {
          key: 'saveTemplate',
          label: '保存模板',
        },
      ],
    },
    columns: {
      type: [Array],
      default: () => [
        {
          align: 'center',
          title: '序号',
          width: 60,
          customRender(t, r, index) {
            return parseInt(index) + 1;
          },
        },
        {
          align: 'center',
          title: '销售组',
          dataIndex: 'salesGroup',
          width: '32%',
          scopedSlots: { customRender: 'salesGroup' },
          required: true,
        },
        {
          align: 'center',
          title: '销售责任人',
          dataIndex: 'responsibleId',
          width: '32%',
          required: true,
          scopedSlots: { customRender: 'responsibleId' },
        },
        {
          align: 'center',
          title: 'KAPM组',
          dataIndex: 'kapmGroup',
          required: true,
          scopedSlots: { customRender: 'kapmGroup' },
        },
      ],
    },
  },
  data() {
    return {
      orgGroupOptions: [],
      orgKapmOptions: [],
      visibleDialog: false,
      visibleDialogUse: false,
    };
  },
  computed: {
    templateData() {
      return (
        this.dataSource.filter((item) => {
          return this.rowSelectionMixin.selectedRowKeys.includes(item.id);
        }) || []
      );
    },
  },
  watch: {
    parentId: {
      handler(val) {
        console.log('val: ', val);
        this.getDicList();
      },
      immediate: true,
    },
  },
  created() {},
  methods: {
    async getDicList() {
      const result = await postOrganizationInfo({
        code: this.parentId,
      });
      const orgOptions = result?.data?.data || [];
      this.orgGroupOptions = orgOptions.filter((item) =>
        item.code?.includes('sales')
      );
      this.orgKapmOptions = orgOptions.filter((item) =>
        item.code?.includes('kapm')
      );
    },
    handleInputChange(e, text, record, index, key) {
      if (key === 'salesGroup') {
        this.dataSource[index]['responsibleId'] = '';
      }
      this.dataSource[index][key] = e;
    },
    handleButtonClick(key) {
      const fn = `${key}Callback`;
      console.log('fn: ', fn);
      this[fn] && this[fn]();
    },
    addCallback() {
      this.dataSource.push({ ...createDefaultItem() });
    },
    deleteCallback() {
      const ids = this.rowSelectionMixin.selectedRowKeys;
      if (!ids.length) {
        this.$message.error('请先选择数据！');
        return;
      }
      this.$confirm(`该操作将删除 ${ids.length} 条数据，是否确认？`)
        .then(() => {
          ids.forEach((id) => {
            const index = this.dataSource.findIndex((item) => item.id === id);
            this.dataSource.splice(index, 1);
          });
          this.rowSelectionMixin.selectedRowKeys = [];
        })
        .catch(() => {
          // console.log('e: ', e);
        });
    },
    saveTemplateCallback() {
      const ids = this.rowSelectionMixin.selectedRowKeys;
      if (!ids.length) {
        this.$message.error('请先选择数据！');
        return;
      }
      this.visibleDialog = true;
    },
    useTemplateCallback() {
      this.visibleDialogUse = true;
    },
    handleDialogUseChange(val) {
      const copys = val.map((item) => {
        return {
          ...item,
          id: `copy_${item.id}`,
          responsibleId: {
            key: item.responsibleId,
            label: item.responsibleName,
          },
          salesGroup: {
            key: item.salesGroup,
            label: item.salesGroupName,
          },
          kapmGroup: {
            key: item.kapmGroup,
            label: item.kapmGroupName,
          },
        };
      });
      this.dataSource.push(...copys);
    },
    handleDialogChange(value) {
      const ids = this.rowSelectionMixin.selectedRowKeys;
      ids.forEach((id) => {
        const index = this.dataSource.findIndex((item) => item.id === id);
        if (index > -1) {
          this.dataSource[index].isTemplate = 1;
          this.dataSource[index].templateName = value;
        }
      });
      this.$message.success('操作成功！');
    },
  },
};
</script>

<style lang="less" scoped>
.item-container {
  display: flex;
  align-items: center;
}
.table-list-container {
  margin-top: 20px;
}

/deep/ .poros-select-selection {
  border: none;
}
</style>
